/*******************************************************************************************
 * Copyright (c) 2006-2009 Alex Robson, Rob Simmons, Craig Israel, and Rachel Twyford
 *
 * Use of this software in any form requires that you have both 
 * read and agreed to the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions: 
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the 
 * documentation and/or other materials provided with the distribution.
 * Neither the name of Nvigorate nor the names of its contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Nvigorate.Common.Reflection;
using Nvigorate.Data.Query;
using Nvigorate.Extensions;

namespace Nvigorate.Relational.Mapping.Fluent
{
    public class FluentSource<TClass> : FluentSourceBase<TClass>
    {
        #region Fields

        #endregion

        #region Public Methods

        /// <summary>
        /// Assigns the property to a column. The convention is to assume the property and column have the same name.
        /// </summary>
        /// <typeparam name="TProperty">The type of the property (unused)</typeparam>
        /// <param name="property">The property to assign</param>
        /// <returns>A fluent assignment</returns>
        public FluentAssignment Assign<TProperty>(Expression<Func<TClass, TProperty>> property)
        {
            var expression = property.Body as MemberExpression;
            var propertyPath = expression.GetPropertyPath().BuildString(".");
            var assignment = new FluentAssignment(Name, typeof(TClass), propertyPath);
            Assignments.Add(assignment);
            return assignment;
        }

        public FluentAssignment Assign(string targetFieldPath)
        {
            var assignment = new FluentAssignment(Name, typeof(TClass), targetFieldPath);
            Assignments.Add(assignment);
            return assignment;
        }

        /// <summary>
        /// A column owned by this table. For use with join criteria
        /// </summary>
        /// <param name="column">The name of the column which belongs to this table</param>
        /// <returns>The column object for use in join criteria</returns>
        public Column Column(string column)
        {
            return Data.Query.Column.Named(column).OwnedBy(Name);
        }

        public FluentSource<TClass> ForbidDelete()
        {
            CanDelete = false;
            return this;
        }

        public FluentSource<TClass> ForbidInsert()
        {
            CanInsert = false;
            return this;
        }

        public FluentSource<TClass> ForbidPersist()
        {
            CanDelete = false;
            CanInsert = false;
            CanUpdate = false;
            return this;
        }

        public FluentSource<TClass> ForbidUpdate()
        {
            CanUpdate = false;
            return this;
        }
        
        /// <summary>
        /// A criteria related to a column owned by this table. For use with join criteria
        /// </summary>
        /// <param name="column">The name of the column which belongs to this table</param>
        /// <returns>The criteria object referencing the column for use in join criteria</returns>
        public Criterion ColumnCriteria(string column)
        {
            return Criterion.Column(column, Name);
        }

        public void Import<TParent>(FluentSourceBase<TParent> parentSource)
        {
            CanDelete = parentSource.CanDelete;
            CanInsert = parentSource.CanInsert;
            CanSelect = parentSource.CanSelect;
            CanUpdate = parentSource.CanUpdate;

            if(parentSource.Join != null)
            {
                Join = Reflector.Clone(parentSource.Join);
                Join.Subject = Name;
            }

            parentSource.Assignments.ForEach(a =>
                {
                    var newAssignment = Reflector.Clone(a);
                    newAssignment.target = TypeName;
                    Assignments.Add(newAssignment);
                });
        }

        /// <summary>
        /// Defines how this table joins to another table for the current type
        /// </summary>
        /// <param name="parentTable">The table to join to</param>
        /// <param name="joinType">The type of join</param>
        /// <param name="joinOn">The criteria to use to join the tables</param>
        /// <returns></returns>
        public FluentSource<TClass> JoinTo(FluentSource<TClass> parentTable, JoinType joinType, SearchCriteria joinOn)
        {
            var join = new LeftJoin()
                           {
                               Subject = Name,
                               Relative = parentTable.Name,
                               JoinCriteria = joinOn
                           };
            Join = join;
            return this;
        }

        /// <summary>
        /// Defines how this table joins to another table for the current type
        /// </summary>
        /// <param name="parentTable">The table to join to</param>
        /// <param name="joinType">The type of join</param>
        /// <param name="joinOn">The criteria to use to join the tables</param>
        /// <returns></returns>
        public FluentSource<TClass> JoinToInherited<TParent>(FluentSource<TParent> parentTable, JoinType joinType, SearchCriteria joinOn)
        {
            var join = new LeftJoin()
                           {
                               Subject = Name,
                               Relative = parentTable.Name,
                               JoinCriteria = joinOn
                           };
            Join = join;
            return this;
        }

        /// <summary>
        /// Defines how this table joins to another table for the current type
        /// </summary>
        /// <param name="parentTable">The table to join to</param>
        /// <param name="joinType">The type of join</param>
        /// <param name="joinOn">The criteria to use to join the tables</param>
        /// <returns></returns>
        public FluentSource<TClass> JoinFromInherited<TParent>(FluentSource<TParent> parentTable, JoinType joinType, SearchCriteria joinOn)
        {
            var join = new LeftJoin()
                           {
                               Subject = parentTable.Name,
                               Relative = Name,
                               JoinCriteria = joinOn
                           };
            Join = join;
            return this;
        }

        public FluentSource<TClass> UseConstructor()
        {
            TargetRequiresConstructor = true;
            return this;
        }

        #endregion
        
        public FluentSource(string name)
        {
            Name = name;
            CanInsert = true;
            CanDelete = true;
            CanSelect = true;
            CanUpdate = true;
            Assignments = new List<FluentAssignment>();
        }
    }

    public class FluentSource<TClass, TSchema> : FluentSourceBase<TClass>
    {
        private Type _schemaType = typeof (TSchema);

        public string TableName
        {
            get
            {
                return Reflector.HasProperty(_schemaType, "TableName") ? Reflector.Read(_schemaType, "TableName").ToString() : _schemaType.Name.Replace("Schema", "");
            }
        }
        
        #region Public Methods

        /// <summary>
        /// Assigns the property to a column. The convention is to assume the property and column have the same name.
        /// </summary>
        /// <typeparam name="TProperty">The type of the property (unused)</typeparam>
        /// <param name="property">The property to assign</param>
        /// <returns>A fluent assignment</returns>
        public FluentAssignment Assign<TProperty>(Expression<Func<TClass, TProperty>> property)
        {
            var expression = property.Body as MemberExpression;
            var propertyPath = expression.GetPropertyPath().BuildString(".");
            var assignment = new FluentAssignment(Name, typeof(TClass), propertyPath);
            Assignments.Add(assignment);
            return assignment;
        }

        /// <summary>
        /// Assigns the property to a column. The convention is to assume the property and column have the same name.
        /// </summary>
        /// <typeparam name="TProperty">The type of the property (unused)</typeparam>
        /// <param name="property">The property to assign</param>
        /// <returns>A fluent assignment</returns>
        public FluentAssignment Assign<TProperty, TColumn>(Expression<Func<TClass, TProperty>> property, Expression<Func<TSchema, TColumn>> column)
        {
            var memberExpression = property.Body as MemberExpression;
            var propertyPath = memberExpression.GetPropertyPath().BuildString(".");
            var assignment = new FluentAssignment(Name, typeof(TClass), propertyPath);
            var columnExpression = column.Body as MemberExpression;
            var columnName = columnExpression.Member.Name;
            assignment.ToColumn(columnName);
            Assignments.Add(assignment);
            return assignment;
        }

        /// <summary>
        /// A criteria related to a column owned by this table. For use with join criteria
        /// </summary>
        /// <param name="column">The name of the column which belongs to this table</param>
        /// <returns>The criteria object referencing the column for use in join criteria</returns>
        public Criterion<TColumn> Column<TColumn>(Expression<Func<TSchema, TColumn>> column)
        {
            var expression = column.Body as MemberExpression;
            var columnName = expression.Member;
            return Criterion.Column<TColumn>(columnName.Name, TableName);
        }

        
        public FluentSource<TClass, TSchema> ForbidDelete()
        {
            CanDelete = false;
            return this;
        }

        public FluentSource<TClass, TSchema> ForbidInsert()
        {
            CanInsert = false;
            return this;
        }

        public FluentSource<TClass, TSchema> ForbidPersist()
        {
            CanDelete = false;
            CanInsert = false;
            CanUpdate = false;
            return this;
        }

        public FluentSource<TClass, TSchema> ForbidUpdate()
        {
            CanUpdate = false;
            return this;
        }

        /// <summary>
        /// Defines how this table joins to another table for the current type
        /// </summary>
        /// <param name="parentTable">The table to join to</param>
        /// <param name="joinType">The type of join</param>
        /// <param name="joinOn">The criteria to use to join the tables</param>
        /// <returns></returns>
        public FluentSourceBase<TClass> JoinTo(FluentSourceBase<TClass> parentTable, JoinType joinType, SearchCriteria joinOn)
        {
            var join = new LeftJoin()
                           {
                               Subject = Name,
                               Relative = parentTable.Name,
                               JoinCriteria = joinOn
                           };
            Join = join;
            return this;
        }

        /// <summary>
        /// Defines how this table joins to another table for the current type
        /// </summary>
        /// <param name="parentTable">The table to join to</param>
        /// <param name="joinType">The type of join</param>
        /// <param name="joinOn">The criteria to use to join the tables</param>
        /// <returns></returns>
        public FluentSourceBase<TClass> JoinToInherited<TParent>(FluentSourceBase<TParent> parentTable, JoinType joinType, SearchCriteria joinOn)
        {
            var join = new LeftJoin()
                           {
                               Subject = Name,
                               Relative = parentTable.Name,
                               JoinCriteria = joinOn
                           };
            Join = join;
            return this;
        }

        /// <summary>
        /// Defines how this table joins to another table for the current type
        /// </summary>
        /// <param name="parentTable">The table to join to</param>
        /// <param name="joinType">The type of join</param>
        /// <param name="joinOn">The criteria to use to join the tables</param>
        /// <returns></returns>
        public FluentSourceBase<TClass> JoinFromInherited<TParent>(FluentSourceBase<TParent> parentTable, JoinType joinType, SearchCriteria joinOn)
        {
            var join = new LeftJoin()
                           {
                               Subject = parentTable.Name,
                               Relative = Name,
                               JoinCriteria = joinOn
                           };
            Join = join;
            return this;
        }

        /// <summary>
        /// A criteria built around the referenced property for use in building join criteria
        /// </summary>
        /// <typeparam name="TProperty">The property for the criteria (gets translated for the database)</typeparam>
        /// <param name="property">The expression which indicates the property</param>
        /// <returns>A strongly typed criteria set to the specific property</returns>
        public Criterion<TProperty> PropertyCriteria<TProperty>(Expression<Func<TClass, TProperty>> property)
        {
            return new DomainCriterion<TClass>().Property(property);
        }

        public Property Property<TProperty>(Expression<Func<TClass, TProperty>> property)
        {
            return new DomainCriterion<TClass>().Property(property).Field as Property;
        }

        public FluentSource<TClass, TSchema> UseConstructor()
        {
            TargetRequiresConstructor = true;
            return this;
        }

        #endregion

        public FluentSource()
        {
            CanInsert = true;
            CanDelete = true;
            CanSelect = true;
            CanUpdate = true;
            Name = TableName;
            Assignments = new List<FluentAssignment>();
        }
    }
}